//
//  ViewController.swift
//  WebViewTest
//
//  Created by 杨岑 on 2018/12/15.
//  Copyright © 2018 杨岑. All rights reserved.
//

import Cocoa
import WebKit

class MainVC: NSViewController, WebUIDelegate, WebFrameLoadDelegate {
    @IBOutlet weak var webView: WebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let html = """
        <h1>test</h1>
        <button onclick='alert(new Date())'>alert</button>
        <button onclick='test1()'>test1</button>
        <button onclick='Cocoa.test(1, "abc", new Date())'>Cocoa.test</button>
        <button onclick='throw "custom error"'>throw</button>
        """
        webView.mainFrame.loadHTMLString(html, baseURL: nil)
    }

    func webView(_ webView: WebView!, didClearWindowObject windowObject: WebScriptObject!, for frame: WebFrame!) {
        windowObject.setValue(self, forKey: "Cocoa")
        
        let js = "function test1() { alert('test1') }"
        webView.windowScriptObject.evaluateWebScript(js)
    }
    
    func webView(_ sender: WebView!, runJavaScriptAlertPanelWithMessage message: String!, initiatedBy frame: WebFrame!) {
        print("JavaScript alert: \(message!)")
    }
    
    override func invokeUndefinedMethod(fromWebScript name: String!, withArguments arguments: [Any]!) -> Any! {
        print("Undefined script: \(name!) with args:")
        for arg in arguments {
            if let o = arg as? WebScriptObject {
                print("..\(o.jsValue()!)")
            } else {
                print("..\(arg)")
            }
        }
        return nil
    }
    
    class func throwException(_ exceptionMessage: String!) -> Bool {
        print("Exception: \(exceptionMessage!)")
        return true
    }
    
    func setException(_ description: String!) -> Bool {
        print("Exception: \(description!)")
        return true
    }
}

